# coding=utf8
from elastalert.alerts import Alerter, BasicMatchString
from elastalert.util import elastalert_logger
from qywx import QywxAuth
from qywx import QywxMessage

try:
    import json
except ImportError:
    import simplejson as json


#
class QywxAlerter(Alerter):
    # By setting required_options to a set of strings
    # You can ensure that the rule config file specifies all
    # of the options. Otherwise, ElastAlert will throw an exception
    # when trying to load the rule.
    required_options = set(['output_file_path'])

    # Alert is called
    def alert(self, matches):
        # Matches is a list of match dictionaries.
        # It contains more than one match when the alert has
        # the aggregation option set
        body = self.create_alert_body(matches)
        content = '系统提醒：\n' + body
        elastalert_logger.info('content length is %s' % len(content))
        # Send to users: znb、jlf
        alert_tousers = self.rule['alert_tousers']
        qywx_appid = 26;

        auth = QywxAuth()
        token = auth.get_token('wxa41a4011c366e488',
                               'N5xabp5-jt6XhuMmR8Fxlhi0iLq0fUdvtrFlHGIEju3azg6KzrmTtGSKCQhp22JH')
        elastalert_logger.info("Get token %s" % token)
        elastalert_logger.info("Sent QYWX message to %s" % (alert_tousers))
        message = QywxMessage()
        message.send_text(token, qywx_appid, content, alert_tousers)

    # get_info is called after an alert is sent to get data that is written back
    # to Elasticsearch in the field "alert_info"
    # It should return a dict of information relevant to what the alert does
    def get_info(self):
        return {'type': 'QywxAlerter',
                'output_file': self.rule['output_file_path']}
